package com.sfac.java_spring_boot_02.listener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.format.annotation.DateTimeFormat;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebListener;
import java.io.File;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @Description LogListener
 * @Author HymanHu
 * @Date 2021/9/16 15:15
 */
@WebListener
public class LogListener implements ServletContextListener {

    private final static Logger LOGGER = LoggerFactory.getLogger(LogListener.class);

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        LOGGER.debug("==== Init LogListener ====");

        // 判断日志文件夹是否存在
        File logFolder = new File( "/var/log");
        if (!logFolder.exists()) {
            return;
        }

        // 拿到当前日期的字符串
        LocalDateTime localDateTime = LocalDateTime.now();
        DateTimeFormatter stf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String currentDate = stf.format(localDateTime);

        // 获取日志文件夹下所有文件列表
        File[] files = logFolder.listFiles();
        // 循环文件列表
        for(File file : files) {
            // 获取每个文件的名字，判断是否包含当前日期，不包含则干掉
            String fileName = file.getName();
            if (!fileName.contains(currentDate)) {
                file.delete();
            }
        }
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        LOGGER.debug("==== Destroyed LogListener ====");
    }
}
